/*
 * Copyright 2002-2021 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.context.support;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.AbstractBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.core.OrderComparator;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import org.springframework.core.metrics.ApplicationStartup;
import org.springframework.core.metrics.StartupStep;
import org.springframework.lang.Nullable;

/**
 * Delegate for AbstractApplicationContext's post-processor handling.
 *
 * @author Juergen Hoeller
 * @author Sam Brannen
 * @since 4.0
 */
final class PostProcessorRegistrationDelegate {

	private PostProcessorRegistrationDelegate() {
	}


	public static void invokeBeanFactoryPostProcessors(
			ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

		// WARNING: Although it may appear that the body of this method can be easily
		// refactored to avoid the use of multiple loops and multiple lists, the use
		// of multiple lists and multiple passes over the names of processors is
		// intentional. We must ensure that we honor the contracts for PriorityOrdered
		// and Ordered processors. Specifically, we must NOT cause processors to be
		// instantiated (via getBean() invocations) or registered in the ApplicationContext
		// in the wrong order.
		//
		// Before submitting a pull request (PR) to change this method, please review the
		// list of all declined PRs involving changes to PostProcessorRegistrationDelegate
		// to ensure that your proposal does not result in a breaking change:
		// https://github.com/spring-projects/spring-framework/issues?q=PostProcessorRegistrationDelegate+is%3Aclosed+label%3A%22status%3A+declined%22

		// Invoke BeanDefinitionRegistryPostProcessors first, if any.
		//TODO 无论任何情况，优先执行BeanDefinitionRegistryPostProcessors
		//TODO 1、【防止重复执行】：事先准备好集合
		// processedBeans：将已经执行过的BeanFactoryPostProcessor存储在processedBeans，防止重复执行
		Set<String> processedBeans = new HashSet<>();

		//TODO 【处理实现了BeanDefinitionRegistryPostProcessor的处理器】
		//TODO 2、【工厂引用类型判断】：判断beanFactory是否是属于BeanDefinitionRegistry类型的，
		// 此处的beanFactory实际使用的子类是DefaultListableBeanFactory——>父类是ConfigurableListableBeanFactory,这里只是用父类进行引用）
		// DefaultListableBeanFactory是实现BeanDefinitionRegistry接口的，所以这里为true
		if (beanFactory instanceof BeanDefinitionRegistry) {
			//TODO 3、【类型转换】
			BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
			//TODO 4、【父子类型的分开处理】：BeanDefinitionRegistryPostProcessor是BeanFactoryPostProcessor子集
			// BeanFactoryPostProcessor:主要针对操作对象是BeanFactory
			// BeanDefinitionRegistryPostProcessor：主要针对的对象是BeanDefinition
			//TODO 存放父类BeanFactoryPostProcessor集合
			List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
			//TODO 存放子类BeanDefinitionRegistryPostProcessor集合
			List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();

			//TODO 【父子类型的分开处理】
			// 对传进来的BeanFactoryPostProcessor进行分类处理，List<BeanFactoryPostProcessor>默认为空
			// 因为BeanFactoryPostProcessor会包含两种类型
			//TODO beanFactoryPostProcessors：该集合默认为空，可以理解为外部的BeanFactoryPostProcessor，用户手动加入的BeanFactoryPostProcessor
			// 也就是自定义的beanFactoryPostProcessor，如果没有自定义则为空，将不执行该循环
			for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
				//TODO 如果postProcessor属于BeanDefinitionRegistryPostProcessor
				if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
					//TODO 进行类型转换
					BeanDefinitionRegistryPostProcessor registryProcessor =
							(BeanDefinitionRegistryPostProcessor) postProcessor;
					//TODO 执行beanDefinitionRegistry处理器，可以发现BeanDefinitionRegistryPostProcessor该类名与postProcessBeanDefinitionRegistry方法有见名之意的效果，
					// 直接执行BeanDefinitionRegistryPostProcessor中的postProcessBeanDefinitionRegistry方法
					registryProcessor.postProcessBeanDefinitionRegistry(registry);
					//TODO 添加到registryProcessors集合中进行记录
					registryProcessors.add(registryProcessor);
				}
				else {
					//TODO 如果处理器不是属于BeanDefinitionRegistryPostProcessor，
					// 只是普通的BeanFactoryPostProcessor 则添加到该regularPostProcessors集合中，还没进行处理
					regularPostProcessors.add(postProcessor);
				}
			}

			// Do not initialize FactoryBeans here: We need to leave all regular beans
			// uninitialized to let the bean factory post-processors apply to them!
			// Separate between BeanDefinitionRegistryPostProcessors that implement
			// PriorityOrdered, Ordered, and the rest.
			//TODO  【为了解决spring运行中有多个增强器BeanFactoryPostProcessor执行顺序的问题】:总体的执行顺序为：PriorityOrdered-》Ordered-》没有实现任何接口排序的对象
			//TODO 5、如果传入的beanFactoryPostProcessors为空：
			// 创建新的集合用来保存本次要执行的BeanDefinitionRegistryPostProcessor
			List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

			// TODO First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
			//  英文翻译：首先，执行实现了PriorityOrdered接口的BeanDefinitionRegistryPostProcessors
			//  PriorityOrdered接口的作用：处理相同接口实现类的优先级问题
			//TODO 6、找到所有的实现了BeanDefinitionRegistryPostProcessor接口的bean的beanName
			// ---------第一次获取postProcessorNames
			String[] postProcessorNames =
					beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			//TODO 7、遍历处理所有符合规则的postProcessorNames 先处理实现PriorityOrdered接口的
			for (String ppName : postProcessorNames) {
				//TODO 检查是否实现了PriorityOrdered接口
				if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
					//TODO 根据名字获取对应的bean实例，添加到currentRegistryProcessors中，【注意】：这里通过getBean()触发实例化BeanDefinitionRegistryPostProcessor操作，并且调用对象
					currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
					//TODO 将要被执行的BeanFactoryPostProcessor名称添加到processedBeans，避免后续重复执行
					processedBeans.add(ppName);
				}
			}
			//TODO 8、按照优先级进行排序操作
			sortPostProcessors(currentRegistryProcessors, beanFactory);
			//TODO 9、将处理好的currentRegistryProcessors添加到registryProcessors中，用于最后执行postProcessorBeanFactory方法
			registryProcessors.addAll(currentRegistryProcessors);
			//TODO 10、遍历currentRegistryProcessors，执行postProcessBeanDefinitionRegistry方法，
			// 在次方法中仍然可以进行扩展，通过代码的信息进行又进行添加新的BeanDefinitionRegistryPostProcessors，所以后面的代码中每次都会继续获取一次BeanDefinitionRegistryPostProcessor.class
			// @Configuration等注解相关类也会在这里进行处理
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
			//TODO 11、执行完毕之后，清空currentRegistryProcessors
			currentRegistryProcessors.clear();

			// TODO Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
			// TODO 12、接下来，调用实现Ordered的BeanDefinitionRegistryPostProcessors。再处理实现Ordered接口的
			//TODO 再次找到所有实现BeanDefinitionRegistryPostProcessor接口的bean的beanName
			// 注意：这里为什么还要重新再找一遍BeanDefinitionRegistryPostProcessor呢？---原因在于上面执行invokeBeanDefinitionRegistryPostProcessors过程中可能会新增其他的BeanDefinitionRegistryPostProcessor
			// ---------第二次获取postProcessorNames
			postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			for (String ppName : postProcessorNames) {
				//TODO 检查是否实现了Ordered接口 Ordered接口的作用：Ordered是PriorityOrdered父类
				if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
					//TODO 根据名字获取对应的bean实例，上面进行清空了，继续进行添加，添加到currentRegistryProcessors中，
					currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
					//TODO 将要被执行的BeanFactoryPostProcessor名称添加到processedBeans，避免后续重复执行
					processedBeans.add(ppName);
				}
			}
			//TODO 13、按照优先级进行排序操作
			sortPostProcessors(currentRegistryProcessors, beanFactory);
			//TODO 14、将处理好的currentRegistryProcessors添加到registryProcessors中，用于最后执行postProcessorBeanFactory方法
			registryProcessors.addAll(currentRegistryProcessors);
			//TODO 15、遍历currentRegistryProcessors，执行postProcessBeanDefinitionRegistry方法
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
			//TODO 16、执行完毕之后，清空currentRegistryProcessors
			currentRegistryProcessors.clear();

			// TODO Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
			//  17、最后，调用所有其他BeanDefinitionRegistryPostProcessors（既没有实现Ordered，也没有实现PriorityOrdered接口的），
			//  直到没有其他BeanDefinitionRegistryPostProcessors出现为止。
			boolean reiterate = true;
			while (reiterate) {
				reiterate = false;
				//TODO  ---------------第三次获取postProcessorNames，
				postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
				for (String ppName : postProcessorNames) {
					//TODO 判断ppName在processedBeans中不存在
					if (!processedBeans.contains(ppName)) {
						//TODO 根据名字获取对应的bean实例，添加到currentRegistryProcessors中
						currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
						//TODO 将要被执行的BeanFactoryPostProcessor名称添加到processedBeans，避免后续重复执行
						processedBeans.add(ppName);
						//TODO 标记为修改状态
						reiterate = true;
					}
				}
				//TODO 到了这里之后既没有实现PriorityOrdered接口也没有实现Ordered接口，那么为什么还需要进行排序呢?
				//TODO 按照优先级进行排序操作
				// 到这里了，就不会说有有实现了Ordered、PriorityOrdered接口的增强器了，只是普通的BeanFactoryPostProcessor，所以排序的意义就不是很大了
				sortPostProcessors(currentRegistryProcessors, beanFactory);
				//TODO 将处理好的currentRegistryProcessors添加到registryProcessors中，用于最后执行postProcessorBeanFactory方法
				registryProcessors.addAll(currentRegistryProcessors);
				//TODO 遍历currentRegistryProcessors，执行postProcessBeanDefinitionRegistry方法
				invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
				//TODO 执行完毕之后，清空currentRegistryProcessors
				currentRegistryProcessors.clear();
			}

			//TODO  Now, invoke the postProcessBeanFactory callback of all processors handled so far.
			// 现在，调用到目前为止处理过的所有处理器的postProcessBeanFactory方法。意思是子类的BeanDefinitionRegistryPostProcessor方法已经都执行完了
			// 开始执行父类的BeanFactoryPostProcessor接口的方法了
			invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
			//TODO regularPostProcessors:这个集合从上面的代码中可以看出，是用来装传进来的集合中非BeanDefinitionRegistryPostProcessor接口
			// 最后，调用	入参beanFactoryPostProcessors中普通beanFactoryPostProcessor的postProcessBeanFactory方法
			invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
		}

		else {
			// Invoke factory processors registered with the context instance.
			//TODO 如果beanFactory不属于BeanDefinitionRegistry类型的，直接执行postProcessBeanFactory方法
			invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
		}

		//TODO 注意：到这里为止，入参的BeanFactoryPostProcessors和容器中的所有的BeanDefinitionRegistryPostProcessor已经全部处理完了,
		// 下面开始处理容器中的所有的BeanFactoryPostProcessor：可能会包含一些实现类，只实现了BeanFactoryPostProcessor,但是并没有实现BeanDefinitionRegistryPostProcessor接口
		// 所以下面代码会进行再获取

		// Do not initialize FactoryBeans here: We need to leave all regular beans
		// uninitialized to let the bean factory post-processors apply to them!
		//TODO 【疑问】-为什么上面处理过一遍了，这里还在处理一遍BeanFactoryPostProcessor接口的处理器呢？？？可以理解为上面的regularPostProcessors,只是处理了传入进来的的BeanFactoryPostProcessor接口的
		//TODO 【开始处理实现BeanFactoryPostProcessor的处理器】：上面的代码已经处理完了BeanDefinitionRegistryPostProcessor处理的接口了
		String[] postProcessorNames =
				beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

		// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
		// Ordered, and the rest.
		//TODO 【顺序逻辑处理】还是按照一样的顺序逻辑：先处理 PriorityOrdered->Ordered->nonOrdered
		// 【思考】这里priorityOrderedPostProcessors集合放的是对象，orderedPostProcessorNames与nonOrderedPostProcessorNames放的是名称是否可以有另外的写法，
		// 也放对象，从而实现一样的功能？--可以
		//TODO 1、创建priorityOrderedPostProcessors集合，用来收集BeanFactoryPostProcessor
		List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
		//TODO 2、创建orderedPostProcessorNames集合，用来收集实现了ordered接口的BeanFactoryPostProcessor名称
		List<String> orderedPostProcessorNames = new ArrayList<>();
		// 修改源码进行另外的写法 ：1、orderedPostProcessorNames也创建对应的对象集合
//		List<BeanFactoryPostProcessor> orderedPostProcessors=new ArrayList<>();
		//TODO 3、创建nonOrderedPostProcessorNames集合，用来收集实现了其他接口的BeanFactoryPostProcessor名称
		List<String> nonOrderedPostProcessorNames = new ArrayList<>();
		// 修改源码进行另外的写法 ：2、nonOrderedPostProcessorNames也创建对应的对象集合
//		List<BeanFactoryPostProcessor> nonOrderedPostProcessors=new ArrayList<>();
		for (String ppName : postProcessorNames) {
			if (processedBeans.contains(ppName)) {
				// skip - already processed in first phase above
				//TODO 如果已经执行过了，则跳过
			}
			//TODO 判断匹配实现了PriorityOrdered接口的BeanFactoryPostProcessor
			else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
				priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
			}
			//TODO 判断匹配实现了Ordered接口的BeanFactoryPostProcessor名称，注意这里只是名称而已
			else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
				orderedPostProcessorNames.add(ppName);
				// 修改源码进行另外的写法:3、这里直接添加对象，不放名称
//				orderedPostProcessors.add(beanFactory.getBean(ppName,BeanFactoryPostProcessor.class));
			}
			else {
				//TODO 其他情况的BeanFactoryPostProcessor名称，注意这里只是名称而已
				nonOrderedPostProcessorNames.add(ppName);
				// 修改源码进行另外的写法:4、这里直接添加对象，不放名称
//				nonOrderedPostProcessors.add(beanFactory.getBean(ppName,BeanFactoryPostProcessor.class));
			}
		}

		// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
		//TODO 首先，执行实现了PriorityOrdered接口的BeanFactoryPostProcessors
		//TODO 对BeanFactoryPostProcessors进行顺序执行
		//修改源码进行另外的写法:5、直接排序
		sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
		//TODO 开始执行BeanFactoryPostProcessors
		//修改源码进行另外的写法:6、执行
		invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

		// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
		//TODO 接下来，执行实现Ordered接口的BeanFactoryPostProcessors
		List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
		for (String postProcessorName : orderedPostProcessorNames) {
			//TODO 根据orderedPostProcessorNames集合名称获取对应的BeanFactoryPostProcessor
			orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
		}
		//TODO 排序orderedPostProcessors
		//修改源码进行另外的写法:6、直接排序
		sortPostProcessors(orderedPostProcessors, beanFactory);
		//TODO 执行orderedPostProcessors
		//修改源码进行另外的写法:7、执行
		invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

		// Finally, invoke all other BeanFactoryPostProcessors.
		//TODO 最后，执行所有的其他的BeanFactoryPostProcessors
		List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
		for (String postProcessorName : nonOrderedPostProcessorNames) {
			//TODO 根据nonOrderedPostProcessorNames名称获取对应的BeanFactoryPostProcessor
			nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
		}
		//TODO 直接进行执行其他的BeanFactoryPostProcessors
		//修改源码进行另外的写法:8、直接执行
		invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);

		// Clear cached merged bean definitions since the post-processors might have
		// modified the original metadata, e.g. replacing placeholders in values...
		//TODO 最后，清理缓存
		beanFactory.clearMetadataCache();
	}

	public static void registerBeanPostProcessors(
			ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {

		// WARNING: Although it may appear that the body of this method can be easily
		// refactored to avoid the use of multiple loops and multiple lists, the use
		// of multiple lists and multiple passes over the names of processors is
		// intentional. We must ensure that we honor the contracts for PriorityOrdered
		// and Ordered processors. Specifically, we must NOT cause processors to be
		// instantiated (via getBean() invocations) or registered in the ApplicationContext
		// in the wrong order.
		//
		// Before submitting a pull request (PR) to change this method, please review the
		// list of all declined PRs involving changes to PostProcessorRegistrationDelegate
		// to ensure that your proposal does not result in a breaking change:
		// https://github.com/spring-projects/spring-framework/issues?q=PostProcessorRegistrationDelegate+is%3Aclosed+label%3A%22status%3A+declined%22
		//TODO 1、【找到所有实现了BeanPostProcessor接口的类】：根据BeanPostProcessor类型找到所有实现了BeanPostProcessor接口的类名称
		String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

		// Register BeanPostProcessorChecker that logs an info message when
		// a bean is created during BeanPostProcessor instantiation, i.e. when
		// a bean is not eligible for getting processed by all BeanPostProcessors.
		//TODO 记录下BeanPostProcessor的目标个数
		//TODO 此处为什么要n+1呢，原因非常简单，在此方法的最后会添加一个BeanPostProcessorChecker
		int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
		//TODO 添加BeanPostProcessorChecker（主要用于记录信息）到beanFactory中
		beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

		// Separate between BeanPostProcessors that implement PriorityOrdered,
		// Ordered, and the rest.
		//TODO 创建一个新的集合，用来存放实现了PriorityOrdered接口的BeanPostProcessor
		List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
		//TODO 定义存放spring内部的BeanPostProcessor
		List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
		//TODO 【名称集合】创建一个新的集合用来存放实现了Ordered接口的BeanPostProcessor的名称
		List<String> orderedPostProcessorNames = new ArrayList<>();
		//TODO 【名称集合】创建一个新的集合存放没有实现了PriorityOrdered接口的BeanPostProcessor的名称
		List<String> nonOrderedPostProcessorNames = new ArrayList<>();
		//TODO 遍历所有的postProcessorNames 名称·
		for (String ppName : postProcessorNames) {
			//TODO 根据postProcessorName判断当前的beanPostProcessor是否实现了PriorityOrdered接口，如果符合则添加到priorityOrderedPostProcessors集合中
			if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
				//TODO 根据ppName获取对应的BeanPostProcessor
				BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
				//TODO 将BeanPostProcessor添加到priorityOrderedPostProcessors中
				priorityOrderedPostProcessors.add(pp);
				//TODO 如果当前的BeanPostProcessor实现了MergedBeanDefinitionPostProcessor，将当前的BeanPostProcessor也添加到internalPostProcessors
				if (pp instanceof MergedBeanDefinitionPostProcessor) {
					internalPostProcessors.add(pp);
				}
			}
			//TODO 根据postProcessorName判断当前的beanPostProcessor是否实现了Ordered接口，如果符合则添加到orderedPostProcessorNames集合中
			else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
				orderedPostProcessorNames.add(ppName);
			}
			else {
				//TODO 如果以上的都不满足，则添加到nonOrderedPostProcessorNames中
				nonOrderedPostProcessorNames.add(ppName);
			}
		}

		// First, register the BeanPostProcessors that implement PriorityOrdered.
		//TODO 首先，对实现了priorityOrdered接口的BeanPostProcessor进行排序
		sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
		//TODO 注册实现priorityOrdered的BeanPostProcessors。
		registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

		// Next, register the BeanPostProcessors that implement Ordered. 接下来，注册实现Ordered的BeanPostProcessors。
		// TODO 根据orderedPostProcessorNames集合创建新的List<BeanPostProcessor>集合
		List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
		for (String ppName : orderedPostProcessorNames) {
			//TODO 根据ppName获取对应的BeanPostProcessor
			BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			orderedPostProcessors.add(pp);
			//TODO 如果是spring内部的BeanPostProcessor
			if (pp instanceof MergedBeanDefinitionPostProcessor) {
				internalPostProcessors.add(pp);
			}
		}
		//TODO 排序：对orderedPostProcessors进行排序
		sortPostProcessors(orderedPostProcessors, beanFactory);
		//TODO 注册实现Ordered的BeanPostProcessors。
		registerBeanPostProcessors(beanFactory, orderedPostProcessors);

		// Now, register all regular BeanPostProcessors. 现在，注册所有常规BeanPostProcessors。
		List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
		for (String ppName : nonOrderedPostProcessorNames) {
			BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			nonOrderedPostProcessors.add(pp);
			//TODO 如果是spring内部的BeanPostProcessor
			if (pp instanceof MergedBeanDefinitionPostProcessor) {
				internalPostProcessors.add(pp);
			}
		}
		//TODO 注册实现所有nonOrdered的BeanPostProcessors。
		registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

		// Finally, re-register all internal BeanPostProcessors. 最后，重新注册所有内部BeanPostProcessors。
		//TODO 对spring内部BeanPostProcessors进行排序
		sortPostProcessors(internalPostProcessors, beanFactory);
		//TODO 注册spring内部BeanPostProcessors
		registerBeanPostProcessors(beanFactory, internalPostProcessors);

		// Re-register post-processor for detecting inner beans as ApplicationListeners,
		// moving it to the end of the processor chain (for picking up proxies etc).
		//TODO 添加ApplicationListenerDetector到beanFactory中，需要把监听器放到集合最后，这里进行重复存放了
		beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
	}

	private static void sortPostProcessors(List<?> postProcessors, ConfigurableListableBeanFactory beanFactory) {
		// Nothing to sort?
		if (postProcessors.size() <= 1) {
			return;
		}
		Comparator<Object> comparatorToUse = null;
		if (beanFactory instanceof DefaultListableBeanFactory) {
			comparatorToUse = ((DefaultListableBeanFactory) beanFactory).getDependencyComparator();
		}
		if (comparatorToUse == null) {
			comparatorToUse = OrderComparator.INSTANCE;
		}
		postProcessors.sort(comparatorToUse);
	}

	/**
	 * Invoke the given BeanDefinitionRegistryPostProcessor beans.
	 */
	private static void invokeBeanDefinitionRegistryPostProcessors(
			Collection<? extends BeanDefinitionRegistryPostProcessor> postProcessors, BeanDefinitionRegistry registry, ApplicationStartup applicationStartup) {
		//遍历postProcessors
		for (BeanDefinitionRegistryPostProcessor postProcessor : postProcessors) {
			StartupStep postProcessBeanDefRegistry = applicationStartup.start("spring.context.beandef-registry.post-process")
					.tag("postProcessor", postProcessor::toString);
			//TODO postProcessBeanDefinitionRegistry 执行对应的处理工作
			postProcessor.postProcessBeanDefinitionRegistry(registry);
			postProcessBeanDefRegistry.end();
		}
	}

	/**
	 * Invoke the given BeanFactoryPostProcessor beans.
	 */
	private static void invokeBeanFactoryPostProcessors(
			Collection<? extends BeanFactoryPostProcessor> postProcessors, ConfigurableListableBeanFactory beanFactory) {

		for (BeanFactoryPostProcessor postProcessor : postProcessors) {
			StartupStep postProcessBeanFactory = beanFactory.getApplicationStartup().start("spring.context.bean-factory.post-process")
					.tag("postProcessor", postProcessor::toString);
			postProcessor.postProcessBeanFactory(beanFactory);
			postProcessBeanFactory.end();
		}
	}

	/**
	 * Register the given BeanPostProcessor beans.
	 */
	private static void registerBeanPostProcessors(
			ConfigurableListableBeanFactory beanFactory, List<BeanPostProcessor> postProcessors) {

		if (beanFactory instanceof AbstractBeanFactory) {
			// Bulk addition is more efficient against our CopyOnWriteArrayList there 批量添加对CopyOnWriteArrayList更有效
			((AbstractBeanFactory) beanFactory).addBeanPostProcessors(postProcessors);
		}
		else {
			for (BeanPostProcessor postProcessor : postProcessors) {
				beanFactory.addBeanPostProcessor(postProcessor);
			}
		}
	}


	/**
	 * BeanPostProcessor that logs an info message when a bean is created during
	 * BeanPostProcessor instantiation, i.e. when a bean is not eligible for
	 * getting processed by all BeanPostProcessors.
	 */
	private static final class BeanPostProcessorChecker implements BeanPostProcessor {

		private static final Log logger = LogFactory.getLog(BeanPostProcessorChecker.class);

		private final ConfigurableListableBeanFactory beanFactory;

		private final int beanPostProcessorTargetCount;

		public BeanPostProcessorChecker(ConfigurableListableBeanFactory beanFactory, int beanPostProcessorTargetCount) {
			this.beanFactory = beanFactory;
			this.beanPostProcessorTargetCount = beanPostProcessorTargetCount;
		}

		@Override
		public Object postProcessBeforeInitialization(Object bean, String beanName) {
			return bean;
		}

		@Override
		public Object postProcessAfterInitialization(Object bean, String beanName) {
			//TODO 1、BeanPostProcessor类型的不检测 2、ROLE_INFRASTRUCTURE这种类型的不检测（spring自己的bean）
			if (!(bean instanceof BeanPostProcessor) && !isInfrastructureBean(beanName) &&
					this.beanFactory.getBeanPostProcessorCount() < this.beanPostProcessorTargetCount) {
				if (logger.isInfoEnabled()) {
					logger.info("Bean '" + beanName + "' of type [" + bean.getClass().getName() +
							"] is not eligible for getting processed by all BeanPostProcessors " +
							"(for example: not eligible for auto-proxying)");
				}
			}
			return bean;
		}

		private boolean isInfrastructureBean(@Nullable String beanName) {
			//TODO 检测当前bean是否是spring自己的bean
			if (beanName != null && this.beanFactory.containsBeanDefinition(beanName)) {
				BeanDefinition bd = this.beanFactory.getBeanDefinition(beanName);
				return (bd.getRole() == RootBeanDefinition.ROLE_INFRASTRUCTURE);
			}
			return false;
		}
	}

}
